import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/request'
import { isURL, isEmpty } from '@/utils/validate'
import { pageRoutes } from '@/router/staticRouter'
import qs from 'qs'
import { layoutV1, layoutV2 } from './config'
// 获取菜单列表, 添加并全局变量保存
let clients = []
clients = clients.concat(layoutV1)
clients = clients.concat(layoutV2)
/**
 * 重写路由的push方法
 * 解决两次访问相同路由地址报错
 */
const routerPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}

Vue.use(Router)

// 模块路由(基于主入口布局页面)
export const moduleRoutes = {
  path: '/',
  component: () => import('@/views/main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口布局' },
  children: [
    {
      path: '/home',
      component: () => import('@/views/modules/home'),
      name: 'home',
      meta: { title: '首页', isTab: true }
    }
  ]
}
const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  routes: pageRoutes.concat(moduleRoutes)
})

router.beforeEach((to, from, next) => {
  // 添加动态(菜单)路由
  // 已添加或者当前路由为页面路由, 可直接访问
  if (window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] || fnCurrentRouteIsPageRoute(to, pageRoutes)) {
    // 复制参数 重定向 在地址栏直接输入路由时，从缓存中获取路由的参数
    let route = window.SITE_CONFIG['dynamicMenuRoutes'].filter(item => item.meta.menuId === to.meta.menuId)[0]
    if (isEmpty(to.params) && !isEmpty(route) && !isEmpty(route.params)) {
      to = { ...to, ...route }
      next(to)
    }
    return next()
  }

  // 获取菜单列表, 添加并全局变量保存
  http.get(`/sys/menu/nav?client=${clients.join(',')}`).then(({ data: res }) => {
    if (res.code !== 0) {
      Vue.prototype.$message.error(res.msg)
      return next({ name: 'login' })
    }
    window.SITE_CONFIG['menuList'] = res.data
    fnAddDynamicMenuRoutes(window.SITE_CONFIG['menuList'])
    next({ ...to, replace: true })
  }).catch(() => {
    next({ name: 'login' })
  })
})

/**
 * 判断当前路由是否为页面路由
 * @param {*} route 当前路由
 * @param {*} pageRoutes 页面路由
 */
function fnCurrentRouteIsPageRoute (route, pageRoutes = []) {
  var temp = []
  for (var i = 0; i < pageRoutes.length; i++) {
    if (route.path === pageRoutes[i].path) {
      return true
    }
    if (pageRoutes[i].children && pageRoutes[i].children.length >= 1) {
      temp = temp.concat(pageRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteIsPageRoute(route, temp) : false
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    let curMenu = menuList[i]
    if (curMenu.children && curMenu.children.length >= 1) {
      // 组装父级名称
      for (const item of curMenu.children) {
        item.parentName = curMenu.parentName ? curMenu.parentName + '/' + curMenu.name : curMenu.name
      }
      temp = temp.concat(curMenu.children)
      continue
    }
    // 组装路由
    var route = {
      path: '',
      component: null,
      name: '',
      meta: {
        ...window.SITE_CONFIG['contentTabDefault'],
        menuId: menuList[i].id,
        title: menuList[i].name,
        v2Flag: layoutV2.indexOf(menuList[i].client) !== -1,
        wholeName: menuList[i].parentName ? menuList[i].parentName + '/' + menuList[i].name : menuList[i].name
      },
      params: {}
    }
    let URL = null
    try {
      // eslint-disable-next-line
      URL = (menuList[i].url || '').replace(/{{([^}}]+)?}}/g, (s1, s2) => eval(s2)) // URL支持{{ window.xxx }}占位符变量
    } catch (e) { }
    if (!URL) {
      console.log(`error url config for eval -`, menuList[i])
      continue
    }
    if (isURL(URL)) {
      // 加入生成参数的方法
      fnSetRouteParams(route, URL)
      route['path'] = route['name'] = `i-${menuList[i].id}`
      route['meta']['iframeURL'] = URL
    } else {
      // 处理有query的url add by yj 20190319 begin
      let result = fnSetRouteParams(route, URL)
      route = result.route
      URL = result.URL.replace(/^\//, '').replace(/_/g, '-')

      // URL = URL.replace(/^\//, '').replace(/_/g, '-')
      // route['path'] = route['name'] = URL.replace(/\//g, '-')
      // 处理有query的url add by yj 20190319 end
      route['component'] = () => import(`@/views/modules/${URL}`)
    }
    routes.push(route)
  }
  if (temp.length >= 1) {
    return fnAddDynamicMenuRoutes(temp, routes)
  }
  // 添加路由
  router.addRoutes([
    {
      ...moduleRoutes,
      name: 'main-dynamic-menu',
      children: routes
    },
    { path: '*', redirect: { name: '404' } }
  ])
  window.SITE_CONFIG['dynamicMenuRoutes'] = routes
  window.SITE_CONFIG['dynamicMenuRoutesHasAdded'] = true
}

/**
 * 路由设置参数 参数放置在路由的 params
 * add by yj 20190319
 * @param {*} route 要设置的路由
 * @param {*} URL URL 使用同个组件 需要变化
 */
function fnSetRouteParams (route, URL) {
  let urlSplit = URL.split('?')
  if (urlSplit && urlSplit.length > 1) {
    URL = urlSplit[0]
    route['path'] = route['name'] = URL.replace(/\//g, '-').concat('__').concat(route['meta']['menuId'])
    try {
      let queryObj = qs.parse(urlSplit[1])
      route['params'] = queryObj
    } catch (e) {
      console.log('route.params.error', e)
    }
  } else {
    route['path'] = route['name'] = URL.replace(/\//g, '-')
  }
  return { route: route, URL: URL }
}

export default router
